package com.buba.uploaddemo.service.impl;

import com.buba.common.result.FileResult;
import com.buba.uploaddemo.service.UploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * @author 张宇飞
 * @Description:
 * @date 2021/9/111:48
 */
@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public FileResult Upload(InputStream inputStream, String fileName) {
        FileResult fileResult = new FileResult();
        //构造一个带指定 Region 对象的配置类 region1()表示华北区域
        Configuration cfg = new Configuration(Region.region1());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "ywHkTlEJx_nVKYUv9OI2QdYtmbYzsECTHU_QVp8q";
        String secretKey = "beX8MQrH4clER5P6hYkiZVecTvvcaNk4os-VEcGZ";
        //七牛云的仓库名
        String bucket = "zhangyufeicangku";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        //这里以文件名作为key
        String key = fileName;
        try {

            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果 判断返回的响应码
                if(response.statusCode==200){
                    fileResult.setSuccess("success");
                    fileResult.setMessage("上传成功！");
                    //返回图片链接地址
                     fileResult.setFileUrl("http://qyqkr2ye9.hb-bkt.clouddn.com/"+fileName);
                     return fileResult;
                }else {
                    fileResult.setError("error");
                    fileResult.setMessage("上传失败！");
                    return fileResult;
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }

        return fileResult ;
    }
}
